interface List {
  id: number;
  name: string;
  parentId: number;
}

interface TreeNode {
  value: number;
  title: string;
  icon?: string;
  children?: TreeNode[];
}

const list: List[] = [
  { id: 1, name: "部门1", parentId: 1 },
  { id: 2, name: "部门1-1", parentId: 1 },
  { id: 3, name: "部门1-2", parentId: 1 },
  { id: 4, name: "部门1-1-1", parentId: 2 },
  { id: 5, name: "部门1-2-1", parentId: 3 },
  { id: 6, name: "部门2", parentId: 6 },
  { id: 7, name: "部门2-1", parentId: 6 },
  { id: 8, name: "部门3", parentId: 6 }
];

function arrayToTree(list: List[]): TreeNode[] {
  const map: { [key: number]: TreeNode } = {};
  const result: TreeNode[] = [];

  list.forEach(item => {
    map[item.id] = {
      value: item.id,
      title: item.name
    };
  });

  list.forEach(item => {
    const node = map[item.id];

    if (item.parentId !== item.id) {
      const parent = map[item.parentId];
      parent.children = parent.children || [];
      parent.children.push(node);
    } else {
      result.push(node);
    }
  });

  return result;
}

// 测试

const resultTree = arrayToTree(list);
console.log(resultTree);
